﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.Utilities;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.PersonService;
using RN.ERP.Web.ModelService;

namespace RN.ERP.Web.Person
{
    public partial class PersonExpSpecialityInfo : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            divsearch.Visible = false;
            if (!IsPostBack)
            {
                GetParams();
            }
        }

        /// <summary>
        /// 获取传递参数
        /// </summary>
        private void GetParams()
        {
            Guid empGuid = Guid.Empty;
            Guid specGuid = Guid.Empty;
            string isMain = string.Empty;
            if (!string.IsNullOrEmpty(Request.QueryString["empGuid"]))
            {
                if (Guid.TryParse(Request.QueryString["empGuid"], out empGuid))
                {
                    hdEmpGuid.Value = empGuid.ToString();
                }
            }
            if (!string.IsNullOrEmpty(Request.QueryString["specGuid"]))
            {
                if (Guid.TryParse(Request.QueryString["specGuid"], out specGuid))
                {
                    hdStatus.Value = "1";
                }
            }
            hdSpecGuid.Value = specGuid.ToString();
            if (!string.IsNullOrEmpty(Request.QueryString["isMain"]))
            {
                hidIsMain.Value = Request.QueryString["isMain"].ToString();
            }
            ////异步调用方法
            if (Request.Params["action"] != null)
            {
                string action = Request.Params["action"];
                switch (action)
                {
                    case "ExpSpecAdd":
                        ExpSpecSave(true, empGuid);
                        break;
                    case "ExpSpecEdit":
                        ExpSpecSave(false, empGuid);
                        break;
                    case "GetExpSpec":
                        GetExpSpec(empGuid.ToString(), specGuid.ToString());
                        break;
                    case "GetSpecDics":
                        GetSpecDics();
                        break;
                    case "GetSpecTitle":
                        GetSpecTitle();
                        break;
                }
            }
        }

        //private void BindDDL()
        //{
        //    using (BasicService.BasicServiceClient client = new BasicServiceClient())
        //    {
        //        var dics = JsonConvert.DeserializeObject<Dictionary<string, string>>(client.GetDictionary("specialty", string.Empty, UserInfo.AreaCode));
        //        selSpecialityName.DataSource = dics;
        //        selSpecialityName.DataValueField = "Key";
        //        selSpecialityName.DataTextField = "Value";
        //        selSpecialityName.DataBind();
        //    }
        //}

        /// <summary>
        ///查询信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="AreaCode"></param>
        private void GetExpSpec(string empGuid, string specGuid)
        {
            if (string.IsNullOrEmpty(empGuid)|| string.IsNullOrEmpty(specGuid))
            {
                var result1 = "{\"result\":1,\"message\":\"参数错误！\"}";
                OutputData(result1);
                return;
            }
            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                var ExpSpec = client.GetExpertSpeciality(specGuid, UserInfo.CurrentArea);
                if (ExpSpec != null)
                {
                    var result = "{\"result\":0,\"data\":" + ExpSpec + "}";
                    OutputData(result);
                }
            }
        }

        /// <summary>
        /// 添加修改信息
        /// </summary>
        private void ExpSpecSave(bool flag, Guid empGuid)
        {
            if (empGuid == Guid.Empty)
            {
                OutputData("{\"Result\":false,\"Message\":\"请先添加人员！\"}");
                return;
            }
            if (Request.Params["data"] == null)
            {
                OutputData("{\"Result\":false,\"Message\":\"数据错误！\"}");
                return;
            }
            string data = Request.Params["data"];//取得客户端提交的数据
            //转化数据对象
            var expSpecList = JsonConvert.DeserializeObject<List<JsonEntity>>(Request.Params["data"]);
            ModelService.tb_Expert_Speciality expSpec = null;
            foreach (var spec in expSpecList)
            {
                var valStr = spec.value.Trim('\"');
                expSpec = JsonConvert.DeserializeObject<ModelService.tb_Expert_Speciality>(valStr);
            }
            if (expSpec != null)
            {
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    string result = "";
                    //执行添加或修改操作
                    if (flag)
                    {
                        expSpec.ID = 0;
                        expSpec.SpecialityGuid =Guid.NewGuid();
                        expSpec.EmpGuid = empGuid;
                        result = client.SaveExpertSpecialityInfo(JsonConvert.SerializeObject(expSpec), UserInfo.CurrentArea);
                    }
                    else
                    {
                        result = client.SaveExpertSpecialityInfo(JsonConvert.SerializeObject(expSpec), UserInfo.CurrentArea);
                    }
                    OutputData(result);
                }
            }
        }

        private void GetSpecDics()
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.ReturnValue = 0;
            result.Message = string.Empty;
            string specName = string.Empty;
            if (!string.IsNullOrEmpty(Request.QueryString["specName"]))
            {
                specName = Request.QueryString["specName"];
                specName = HttpUtility.UrlDecode(specName);
            }
            using (BasicService.BasicServiceClient client =new BasicServiceClient())
            {
               var items = JsonConvert.DeserializeObject<List<ModelService.T_Sys_Dict>>(client.GetSysDicts("ExpSpec", string.Empty, string.Empty));
               int targetSID = -1;
               var rec = items.Where(o => o.Name.Contains(specName)).FirstOrDefault();
               var nodelist=new List<NodeEntity>();
               if (rec != null)
               {
                   targetSID = rec.SID;
                   while (rec.ParentSID != 0)
                   {
                       rec = items.Where(o => o.SID == rec.ParentSID).FirstOrDefault();
                   }

                   result.Result = true;
                   result.ReturnValue = rec.SID;
                   result.Message = targetSID.ToString();
               }
            }
            OutputData(JsonConvert.SerializeObject(result));
        }

        private void GetSpecTitle()
        {
            OperationResult result = new OperationResult();
            result.Result = false;
            result.ReturnValue = 0;
            result.Message = string.Empty;
            string id = string.Empty;
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                id = Request.QueryString["id"];
            }
            int sid = -1;
            if(int.TryParse(id,out sid))
            {
                using (PersonService.PersonServiceClient client = new PersonServiceClient())
                {
                    result.Message = client.GetSpecialityTitle(sid, string.Empty);
                    if (!string.IsNullOrEmpty(result.Message))
                    {
                        result.Message = HttpUtility.HtmlDecode(result.Message);
                        result.Result = true;
                    }
                }
            }
            OutputData(JsonConvert.SerializeObject(result));
        }

       


        /// <summary>
        /// 输出JSON格式数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void OutputData(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }

        public override bool IsCheckPermission
        {
            get { return false; }
        }
    }
}